package com.fighYo.trace.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fighYo.trace.entity.Info;
import com.fighYo.trace.entity.Product;
import com.fighYo.trace.entity.Species;
import com.fighYo.trace.entity.User;
import com.fighYo.trace.entity.query.ProductQuery;
import com.fighYo.trace.entity.vo.ProductVo;
import com.fighYo.trace.entity.vo.UserVo;
import com.fighYo.trace.service.InfoService;
import com.fighYo.trace.service.ProductService;
import com.fighYo.trace.service.SpeciesService;
import com.fighYo.trace.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fighYo
 * @since 2022-04-04
 */
@CrossOrigin
@Api(tags = {"产品管理"})
@Slf4j
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private SpeciesService speciesService;

    @Autowired
    private InfoService infoService;

    @ApiOperation("根据产品ID获取产品信息")
    @GetMapping("get")
    public R getProduct(String productId) {
        Product product = productService.getById(productId);
        return R.ok().data("item", product);
    }

    @ApiOperation("添加产品")
    @PostMapping("add")
    public R addProduct(@RequestBody Product product, HttpServletRequest request) {
        String userId = request.getHeader("access-token");

        Species species = speciesService.getById(product.getSpeciesId());

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.eq("species_id", species.getId());

        if (productService.getOne(wrapper) != null) {
            return R.error().msg("该商品已录入");
        }

        if (species.getYield() != null) {
            product.setQuantity(species.getYield() * product.getArea());
        } else {
            product.setQuantity(-1);
        }

        product.setSaleFlag("0");
        product.setUserId(userId);
        product.setJudgeFlag("0");

        boolean result = productService.save(product);
        return result ? R.ok() : R.error().msg("添加失败");
    }

    @ApiOperation("修改产品")
    @PostMapping("update")
    public R updateProduct(@RequestBody Product product) {
        Product temp = productService.getById(product.getId());
        if (!temp.getJudgeFlag().equals("1")) {
            product.setJudgeFlag("0");
        }
        boolean result = productService.updateById(product);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("删除产品")
    @PostMapping("delete")
    public R deleteProduct(@RequestBody Product product) {
        boolean result = productService.removeById(product.getId());
        return result ? R.ok() : R.error();
    }

    @ApiOperation("上架产品")
    @PostMapping("up")
    public R upProduct(@RequestBody Product product) {
        product = productService.getById(product.getId());
        product.setSaleFlag("1");
        boolean result = productService.updateById(product);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("下架产品")
    @PostMapping("down")
    public R downProduct(@RequestBody Product product) {
        product = productService.getById(product.getId());
        product.setSaleFlag("0");
        boolean result = productService.updateById(product);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("根据当前用户获取产品列表")
    @PostMapping("listByUser")
    public R getProductByUser(HttpServletRequest request) {
        String userId = request.getHeader("access-token");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        List productList = productService.list(wrapper);
        return R.ok().data("list", productList);
    }

    @ApiOperation("获取指定用户产品列表")
    @PostMapping("listByUserId")
    public R getProductByUserId(@RequestBody User user) {
        Integer userId = user.getId();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.eq("sale_flag", "1");
        List productList = productService.list(wrapper);
        return R.ok().data("list", productList);
    }

    @PostMapping("page/{cur}/{limit}")
    public R pageTeacherCondition(@PathVariable("cur") long cur,
                                  @PathVariable("limit") long limit,
                                  @RequestBody ProductQuery productQuery) {
        Page<Product> page = new Page<>(cur, limit);

        QueryWrapper<Product> wrapper = new QueryWrapper<>();

        String userName = productQuery.getUserName();
        String productName = productQuery.getProductName();
        String saleFlag = productQuery.getSaleFlag();
        String judgeFlag = productQuery.getJudgeFlag();


        if(!StringUtils.isEmpty(userName)) {
            QueryWrapper<Info> infoWrapper = new QueryWrapper();
            infoWrapper.like("name", userName);
            List<String> userIdList = infoService.list(infoWrapper).stream().map(info -> info.getUserId()).collect(Collectors.toList());
            userIdList.add("-1");
            log.info("userIdList: {}", userIdList);
            wrapper.in("user_id", userIdList);
        }

        if(!StringUtils.isEmpty(productName)) {
            wrapper.like("product_name", productName);
        }

        if(!StringUtils.isEmpty(saleFlag)) {
            wrapper.like("sale_flag", saleFlag);
        }

        if(!StringUtils.isEmpty(judgeFlag)) {
            wrapper.like("judge_flag", judgeFlag);
        }

        productService.page(page, wrapper);

        long total = page.getTotal();
        List<ProductVo> records = page.getRecords().stream()
                .map(product -> productService.getProductVo(product))
                .collect(Collectors.toList());
        return R.ok().data("total", total).data("list", records);
    }

    @ApiOperation("审批产品")
    @PostMapping("/judge")
    public R judgeUser(@RequestBody Product product) {
        Integer id = product.getId();
        String judgeFlag = product.getJudgeFlag();
        product = productService.getById(id);
        product.setJudgeFlag(judgeFlag);
        boolean result = productService.updateById(product);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("获取产品详细信息")
    @GetMapping("/detail")
    public R detail(String id) {
        Product product = productService.getById(id);
        return R.ok().data("item", productService.getProductVo(product));
    }

}

